package com.ksr.logistics.service.impl;

import com.github.pagehelper.PageHelper;
import com.ksr.logistics.mapper.UserMapper;
import com.ksr.logistics.pojo.User;
import com.ksr.logistics.pojo.UserExample;
import com.ksr.logistics.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.swing.*;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> selPageUsers(@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "10")Integer pageSize, String keyWord) {
        UserExample example=new UserExample();
        example.setOrderByClause("user_id desc");
        if (StringUtils.isNotBlank(keyWord)){
            UserExample.Criteria criteria=example.createCriteria();
            criteria.andUsernameLike("%"+keyWord+"%");
            UserExample.Criteria c2=example.createCriteria();
            c2.andRealnameLike("%"+keyWord+"%");
            example.or(c2);
        }
        PageHelper.startPage(page,pageSize);
        List<User> users = userMapper.selectByExample(example);
        return users;
    }

    @Override
    public int deleteById(Integer id) {
        return userMapper.deleteByPrimaryKey((long)id);
    }

    @Override
    public int deleteByIds(List<Integer> ids) {
        int row=0;
        for (Integer id:ids) {
            row+=userMapper.deleteByPrimaryKey((long)id);
        }
        return row;
    }

    @Override
    public User selById(Integer id) {
        return userMapper.selectByPrimaryKey((long)id);
    }


    @Override
    public int insertUser(User user) {
        return userMapper.insert(user);
    }

    @Override
    public int updateUser(User user) {
        return userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public List<User> selByUsername(String username) {
        UserExample example=new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        return userMapper.selectByExample(example);
    }

    @Override
    public List<User> selByRoleID(Integer roleId) {
        UserExample example=new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andRoleIdEqualTo((long) roleId);
        return userMapper.selectByExample(example);
    }


    @Override
    public List<User> selUsersByRoleName(String roleName) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andRolenameEqualTo(roleName);
        return userMapper.selectByExample(example);
    }
}
